<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';
	
	$album_id = intval($_GET['album_id']);
	$direction_check = intval($_GET['direction']);
	$top = intval($_GET['top']);
	
	if($album_id && ($direction_check == 1 || $direction_check == -1)) {
	
		# Get the current order number
		$sql = "SELECT 
				  order_number
				FROM
				  album
				WHERE
				  album_id = ".$album_id."
				";
		$result = query($sql);
		$row = mysql_fetch_assoc($result);
		$old_order_number = $row['order_number'];
		
		# Get the ID of replaced element
		$sql = "SELECT
				   album_id
				FROM
				   album
				WHERE
				   order_number = ".$old_order_number." + (".$_GET['direction'].")
				 ";
		$result = query($sql);
		$row = mysql_fetch_assoc($result);
		$replaced_album_id = $row['album_id'];
		 
		# Move current element one position
		$sql = "UPDATE 
				   album
				SET
				  order_number = order_number + (".$_GET['direction'].") 
				WHERE
				   album_id = '".$album_id."' 
				 ";
		query($sql);
		
		# Move replaced element to currect element's place
		# Update order of replaced element
		$sql = "UPDATE 
				   album
				SET
				  order_number = ".$old_order_number." 
				WHERE
				   album_id = '".$replaced_album_id."'
				 ";
		query($sql);
    
  	}elseif ($album_id && $top==1) {
	  
	$sql = 'SELECT MAX(order_number) AS max_order_number FROM album';
	$row = mysql_fetch_assoc(query($sql));
	$max_order_number = $row['max_order_number'];
	  
	$sql = "SELECT
			  order_number
			FROM
			  album
			WHERE
			  album_id = '$album_id'
              ";
    query($sql);
	$row = mysql_fetch_assoc(query($sql));
	$order_number = $row['order_number'];
	
	$sql = "UPDATE
              album
            SET
              order_number = order_number - 1
            WHERE
              order_number > '$order_number'
              ";
    query($sql);
	
	$sql = "UPDATE
              album
            SET
              order_number = $max_order_number
            WHERE
              album_id = '$album_id'
              ";
    query($sql);
	  
  }
  
  redirect("albums.php#".$album_id);
?>